#!/bin/sh
#
#   http://code.google.com/media-translate/
#   Copyright (C) 2010  Serge A. Timchenko
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#

#
# Translate CGI module
# 'youtube.com' plug-in
#
# version: 2.0 09.12.2010 22:42
#
# http://www.youtube.com/v/JZtcw6GIxTY
# http://www.youtube.com/watch?v=JZtcw6GIxTY
#
# options:
#   HD:[0|1]

local TIMELIFE=60

get_opt "HD"
[ -z "$opt" ] && opt=$YOUTUBE_HD
case $opt in
  yes|Yes|YES|1)
    hdc=$opt
  ;;
  *)
    hdc=''
esac

local video_id=`echo "$arg_url" | sed -e 's/.*v=//;s/.*\///;s/&.*//'`
local CACHEFILE=$CACHEPATH/yt.$video_id

stream_type='video/mp4'
stream_url=''
server_type='youtube'
protocol='http'

local tsttime=
local fmt_url_map=
local hd_param=

let tsttime=`date +%s`-$TIMELIFE

if [ -f $CACHEFILE ]; then
  if [ `date +%s -r $CACHEFILE` -gt $tsttime ]; then
    fmt_url_map=`sed -ne "1p" $CACHEFILE`
    hd_param=`sed -ne "2p" $CACHEFILE`
    icy_name=`sed -ne "3p" $CACHEFILE`
  fi
fi

if [ -z "$t_param" ]; then   
    host_response=`$MSDL -q -o ${TMPFILE} -p http --useragent "${USERAGENT}" http://www.youtube.com/watch?v=$video_id 2>&1`
    if [ -f ${TMPFILE} ]; then
      fmt_url_map=`grep -i 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' ${TMPFILE} | /usr/local/etc/awk '{match($0, /&fmt_url_map=([^&]*)&/, arr);print arr[1];}' | urldecode`
      hd_param=`sed -ne "/'IS_HD_AVAILABLE': /p" ${TMPFILE} | sed -e "s/.*'IS_HD_AVAILABLE': //;s/,.*//"`
      icy_name=`grep 'meta name="title"' ${TMPFILE} | sed 's/.*t="//;s/".*//'`
      icy_name=`unescapeXML "$icy_name"`
      icy_name=`unescapeXML "$icy_name"`
      echo $fmt_url_map > $CACHEFILE
      echo $hd_param >> $CACHEFILE
      echo $icy_name >> $CACHEFILE
      rm -f $TMPFILE
    fi
fi

if [ -n "$hdc" -a "$hd_param" = "true" ]; then
  #22
  stream_url=`echo $fmt_url_map | /usr/local/etc/awk '{match($0,/.*22\|([^,]+),?/,arr);print arr[1]}'`
else
  #18
  stream_url=`echo $fmt_url_map | /usr/local/etc/awk '{match($0,/.*18\|([^,]+),?/,arr);print arr[1]}'`
fi

if [ -n "$fmt_url_map" ]; then
  return $RC_OK
fi

return $RC_FAIL

